package com.xtc.netty.protocol.http.xml.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IMarshallingContext;

import java.io.StringWriter;
import java.nio.charset.Charset;

/**
 * http+xml协议编码抽象类
 *
 * @author Administrator
 */
public abstract class AbstractHttpXmlEncoder<T> extends MessageToMessageEncoder<T> {

    static final String CHARSET_NAME = "UTF-8";

    public static final Charset UTF_8 = Charset.forName(CHARSET_NAME);

    protected ByteBuf encode0(ChannelHandlerContext ctx, Object body) throws Exception {
        IBindingFactory factory = BindingDirectory.getFactory(body.getClass());

        StringWriter writer = new StringWriter();

        IMarshallingContext context = factory.createMarshallingContext();
        context.setIndent(2);
        context.marshalDocument(body, CHARSET_NAME, null, writer);

        String bodyXml = writer.toString();
        writer.close();

        return Unpooled.copiedBuffer(bodyXml, UTF_8);
    }


}
